package com.sky.service.impl;

import com.sky.constant.MessageConstant;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.service.UserService;
import com.sky.thirdparty.WeChatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WeChatService weChatService;

    @Transactional
    @Override
    public User weChatLogin(String code) {
        // 1. 发起请求获取微信 openid
        String openid = weChatService.getOpenid(code);
        if (openid == null) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        // 2. 检查openid是否有注册过
        User user = userMapper.getUserByOpenid(openid);
        // 2.1 如果没注册，则先进行注册
        if (user == null) {
            user = register(openid);
        }
        return user;
    }

    /**
     * 注册用户
     *
     * @param openid 微信 openid
     * @return 用户信息
     */
    private User register(String openid) {
        User user = new User();
        user.setOpenid(openid);
        user.setName("用户" + openid);
        user.setCreateTime(LocalDateTime.now());
        userMapper.insert(user);
        return user;
    }

}
